package org.shoukaiseki.inittable.controller;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageSerializable;
import org.shoukaiseki.inittable.domain.SksInitTableVersionQO;
import org.shoukaiseki.inittable.exception.InitTableException;
import org.shoukaiseki.inittable.logger.InitTableLoggers;
import org.shoukaiseki.inittable.service.ITableBuildService;
import org.shoukaiseki.supersaiyan.common.core.domain.base.AjaxResult;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/init/table")
public class TableBuildController {


    public static final Logger logger = InitTableLoggers.DEFAULT_LOGGER;

    private static boolean firstRun=true;

    @Resource
    ITableBuildService tableBuildService;


    @GetMapping("/initTableToVersion")
    public AjaxResult initTableToVersion(boolean reset )  {

        Object o =null;

        o=tableBuildService.initTableToVersion(reset);
        if(reset=true){
            firstRun=true;
        }

        AjaxResult success = AjaxResult.success();
        return success;
    }

   //@PreAuthorize("@ss.hasRole('admin')")
   @PostMapping("/getInitTableList")
   public AjaxResult getInitTableList(@RequestBody SksInitTableVersionQO sksInitTableVersionQO) {

       List o = null;
       if (firstRun) {
           firstRun = false;
           tableBuildService.initTableToVersion(false);
       }

       o = tableBuildService.getInitTableList(sksInitTableVersionQO);

       PageSerializable<Object> page = new PageSerializable<>();
       page.setList(o);
       page.setTotal(new PageInfo(o).getTotal());

       return AjaxResult.successData(page);
   }

       /**
        * 查询客户管理列表
     * @param initType  31:初始化所有,&1:初始化表,&2:重建索引,&4:重建触发器
     */
   //@PreAuthorize("@ss.hasRole('admin')")
    @PostMapping("/build")
    public AjaxResult build(String[] tables,@RequestParam(name = "initType",defaultValue = "255") Integer initType)  {

        Object o =null;
        try{
        o=tableBuildService.initTableBuild(tables,initType);
        }catch (InitTableException e){
            AjaxResult success = AjaxResult.success(e.getMessage(), e.getData());
            success.put("errorFlag",true);
            return success;
        }catch (Throwable t){
            AjaxResult success = AjaxResult.success(t.getMessage());
            success.put("errorFlag",true);
            return success;
        }
        AjaxResult success = AjaxResult.success("初始化完成", o);
        return success;
    }
}
